import request from './request'
const SIZE = 1024 * 1024 * 10 //100MB
const upload = async (files, props) => {
    if (!files) return
    //创建文件切片
    const createFileChunks = (files, size = SIZE) => {
        const fileChunks = []
        for (let cur = 0; cur < files.size; cur += size) {
            fileChunks.push(files.slice(cur, cur + size))
        }
        return fileChunks;
    }

    //上传切片
    const uploadFileChunks = async (fileChunks, filename) => {
        const formDataList = fileChunks.map((chunk, index) => {
            let formData = new FormData();
            formData.append('filename', filename);
            formData.append('hash', index);
            formData.append('chunk', chunk);
            return formData
        });
        const axiosList = formDataList.map((formDataItem) => {
            request.post('/JFChatMsg/upload', formDataItem).then(res => {
                console.log(res);
            })
        })

        //并发上传
        await Promise.all(axiosList)
    }

    //合并切片
    const mergeFileChunks = async (filename) => {
        console.log(filename, 'asfasg');
        request.post('/JFChatMsg/merge', { filename }).then(res => {
            //定义要发送的内容
            let objs = {
                to_id: props.detail.toId,
                msg: res.data.url,
                headImg: "https://pic3.zhimg.com/80/v2-437f4dc41f0f972f31921a228641cf9e_720w.jpg?source=1940ef5c",
                name: props.detail.remark
            }
            //向后台发送消息
            props.ws.send(objs)
        })
    }

    try {
        const fileChunks = createFileChunks(files)
        await uploadFileChunks(fileChunks, files.name)
        await mergeFileChunks(files.name)
        console.log('上传成功');
    } catch (error) {
        console.log('上传失败');
    }
}
export default upload